#include <windows.h>
#pragma comment(lib,"Advapi32.lib")
#include "RegPlus.h"



UINT	RegSave(const char* szKey,const char * szValName,void *buffer,unsigned int nsize)
{
	HKEY  hKey = NULL ;
	
	DWORD	dwRet = 0 ;

	dwRet = RegOpenKey(HKEY_LOCAL_MACHINE,szKey,&hKey);

	if (ERROR_SUCCESS != dwRet )
	{
		dwRet = RegCreateKey(HKEY_LOCAL_MACHINE,szKey,&hKey);
		if (NO_ERROR != dwRet)
		{
			return dwRet ;
		}
	}
	
	dwRet = RegSetValueEx(hKey,szValName,0,REG_BINARY,buffer,nsize);

	if (NO_ERROR != dwRet)
	{
		return dwRet ;
	}

	dwRet = RegCloseKey(hKey);
	if (NO_ERROR != dwRet)
	{
		return dwRet ;
	}

	return  NO_ERROR;
}

UINT  RegGetVal(const char* szKey,const char * szValName,OUT VOID *lpbuffer,unsigned int nsize,OUT UINT * lpretsize)
{

	HKEY  hKey = NULL ;
	
	DWORD	dwRet = 0 ;

	BYTE	bReadTmpBuffer[1024] = { 0 };

	DWORD	cbData = 0 ; 

	DWORD	dwRegType = 0 ;

	
	dwRet = RegOpenKey(HKEY_LOCAL_MACHINE,szKey,&hKey);

	if (hKey)
	{
		dwRet = RegQueryValueEx(hKey,szValName,NULL,&dwRegType,NULL,&cbData);

		if (REG_BINARY == dwRegType  && cbData < sizeof(bReadTmpBuffer) )
		{
			dwRet = RegQueryValueEx(hKey,szValName,NULL,&dwRegType,&bReadTmpBuffer[0],&cbData);
		}

		dwRet = RegCloseKey(hKey);
	}
	else
	{
		//read reg error
		return 1;
	}

	if (lpretsize)
	{
		*lpretsize = cbData;
	}

	if (lpbuffer)
	{
		memcpy(lpbuffer,bReadTmpBuffer,min(cbData,nsize));
	}

	return NO_ERROR;
}